package com.tanhua.dubbo.server.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service(version = "1.0.0")
public class ChuanYinApiImpl implements ChuanYinApi {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private static final String CHUANYIN_REDIS_KEY_PREFIX = "CHUANYIN_";

    @Override
    public Integer queryCount(Long id) {
        //  计算今晚时间毫秒值
        String today = DateUtil.today();
        Long maxDate = DateUtil.parseDateTime(today + " 23:59:59").getTime();

        String redisKey = CHUANYIN_REDIS_KEY_PREFIX + id;

        Boolean bool = redisTemplate.hasKey(redisKey);
        if (!bool) {
            redisTemplate.opsForValue().set(redisKey, "10",maxDate-System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }
        Integer count = Convert.toInt(redisTemplate.opsForValue().get(redisKey));
        count--;
        redisTemplate.opsForValue().set(redisKey, count.toString(),maxDate-System.currentTimeMillis(),TimeUnit.MILLISECONDS);

        return count;
    }
}
